package com.smallkingson.ylib.core.utils;

import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.os.Build.VERSION_CODES;
import android.util.Log;

/**
 * Created by yorun on 2017/7/27.
 */

public class YMediaCodes {

  /**
   * Returns the first codec capable of encoding the specified MIME type, or null if no
   * match was found.
   */
  public static MediaCodecInfo selectCodec(String mimeType) {
    int numCodecs = MediaCodecList.getCodecCount();
    for (int i = 0; i < numCodecs; i++) {
      MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);

      if (!codecInfo.isEncoder()) {
        continue;
      }

      String[] types = codecInfo.getSupportedTypes();
      for (int j = 0; j < types.length; j++) {
        if (types[j].equalsIgnoreCase(mimeType)) {
          return codecInfo;
        }
      }
    }
    return null;
  }
  /**
   * Returns a color format that is supported by the codec and by this test code.  If no
   * match is found, this throws a test failure -- the set of formats known to the test
   * should be expanded for new platforms.
   */
  public static int selectColorFormat(MediaCodecInfo codecInfo, String mimeType) {
    MediaCodecInfo.CodecCapabilities capabilities = codecInfo.getCapabilitiesForType(mimeType);
    for (int i = 0; i < capabilities.colorFormats.length; i++) {
      int colorFormat = capabilities.colorFormats[i];
      if (isRecognizedFormat(colorFormat)) {
        return colorFormat;
      }
    }
    return 0;   // not reached
  }
  /**
   * Returns true if this is a color format that this test code understands (i.e. we know how
   * to read and generate frames in this format).
   */
  public static boolean isRecognizedFormat(int colorFormat) {
    switch (colorFormat) {
      // these are the formats we know how to handle for this test
      case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar:
      case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedPlanar:
      case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar:
      case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedSemiPlanar:
      case MediaCodecInfo.CodecCapabilities.COLOR_TI_FormatYUV420PackedSemiPlanar:
        return true;
      default:
        return false;
    }
  }
  public static void swapYV12toI420(byte[] yv12bytes, byte[] i420bytes, int width, int height) {
    System.arraycopy(yv12bytes, 0, i420bytes, 0, width * height);
    System.arraycopy(yv12bytes, width * height + width * height / 4, i420bytes, width * height,
        width * height / 4);
    System.arraycopy(yv12bytes, width * height, i420bytes, width * height + width * height / 4,
        width * height / 4);
  }
}
